import 'dart:math' as math;

import 'package:flutter/material.dart';

extension $Color on Color {
  static get randomColor {
    math.Random random = math.Random();
    int r = random.nextInt(256) % 255;
    int g = random.nextInt(256) % 255;
    int b = random.nextInt(256) % 255;
    return Color.fromRGBO(r, g, b, 1.0);
  }

  static Color fromWhite(double white, {double alpha = 1.0}) {
    alpha = math.max(0.0, math.min(1.0, alpha));

    white = math.max(0.0, math.min(1.0, white));
    int rgb = (white * 255).toInt();
    return Color.fromRGBO(rgb, rgb, rgb, alpha);
  }

  /// String is in the format "aabbcc" or "ffaabbcc" with an optional leading "#".
  static Color fromHex(String hexString) {
    if (hexString.length < 6) {
      debugPrint('十六进制颜色字符串错误:$hexString，返回透明色。');
      return Colors.transparent;
    }

    final buffer = StringBuffer();
    if (hexString.length == 6 || hexString.length == 7) buffer.write('ff');
    buffer.write(hexString.replaceFirst('#', ''));
    return Color(int.parse(buffer.toString(), radix: 16));
  }

  /// Prefixes a hash sign if [leadingHashSign] is set to `true` (default is `true`).
  String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}'
      '${alpha.toRadixString(16).padLeft(2, '0')}'
      '${red.toRadixString(16).padLeft(2, '0')}'
      '${green.toRadixString(16).padLeft(2, '0')}'
      '${blue.toRadixString(16).padLeft(2, '0')}';
}
